Checking form input data on submit with pure PHP [migrated]

Posted by Leron on Programmers See other posts from Programmers or by Leron
Published on 2012-11-18T21:44:28Z Indexed on 2012/11/18 23:27 UTC
Read the original article Hit count: 279

Filed under:
|
|

I have some experience with PHP but I have never even try to do this wit pure PHP, but now a friend of mine asked me to help him with this task so I sat down and write some code. What I'm asking is for opinion if this is the right way to do this when you want to use only PHP and is there anything I can change to make the code better. Besides that I think the code is working at least with the few test I made with it.

Here it is:

<?php
session_start();

// define variables and initialize with empty values
    $name = $address = $email = "";
    $nameErr = $addrErr = $emailErr = "";
    $_SESSION["name"] = $_SESSION["address"] = $_SESSION["email"] = "";
    $_SESSION["first_page"] = false;


    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["name"])) {
            $nameErr = "Missing";
        }
        else {
            $_SESSION["name"] = $_POST["name"];
            $name = $_POST["name"];
        }

        if (empty($_POST["address"])) {
            $addrErr = "Missing";
        }
        else {
            $_SESSION["address"] = $_POST["address"];
            $address = $_POST["address"];
        }

        if (empty($_POST["email"]))  {
            $emailErr = "Missing";
        }
        else {
            $_SESSION["email"] = $_POST["email"];
            $email = $_POST["email"];
        }
    }
    if ($_SESSION["name"] != "" && $_SESSION["address"] != "" && $_SESSION["email"] != "") {
    $_SESSION["first_page"] = true;
    header('Location: http://localhost/formProcessing2.php');
    //echo $_SESSION["name"]. " " .$_SESSION["address"]. " " .$_SESSION["email"];
    }
?>
<DCTYPE! html>
<head>
<style>
.error {
    color: #FF0000;
}
</style>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type="text" name="name" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span>
<br />
Address <input type="text" name="address" value="<?php echo htmlspecialchars($address);?>">
<span class="error"><?php echo $addrErr;?></span>
<br />
Email <input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span>
<br />
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

© Programmers or respective owner

Related posts about php

Related posts about code-quality